<?php
class UserChar extends AppModel
{
    public $name = 'UserChar';
    public $primaryKey = '_id';
    //public $useDbConfig = 'zeus_db';

    public function get_nick_user($_db_name, $_nick)
    {
        $this->useDbConfig = $_db_name['user_data'];
        $params = array(
            'conditions' => array(
                'nick_name' => $_nick
            )
        );

        $data = $this->find('first', $params);
        return $data;
    }

    public function get_char_all($_db_name)
    {
        $this->useDbConfig = $_db_name['user_data'];
        $params = array(
            'order' => array('level' => 'ASC')
        );
        $data = $this->find('all', $params);
        return $data;
    }

    public function get_char($_db_name, $_usn)
    {
        $this->useDbConfig = $_db_name['user_data'];
        $params = array(
            'conditions' => array(
                'usn' => $_usn
            ),
        );
        $data = $this->find('all', $params);
        return $data;
    }

    public function char_del($_db_name, $_usn, $_char_id)
    {
        $this->useDbConfig = $_db_name['user_data'];

        $params = array('usn' => $_usn);
        if( !$this->deleteall($params) )
            return false;

        return true;
    }

    public function delect_all($_db_name)
    {
        $this->useDbConfig = $_db_name['user_data'];
        $this->deleteAll(array('_id not' => null));
        return true;
    }

    public function stage_save($_db_name, $_id, $_stage)
    {
        $this->useDbConfig = $_db_name['user_data'];
        $this->id = $_id;
        $data['stage_clear'] = $_stage;
        if( !$this->save($data) )
        {
            return false;
        }
        return true;
    }

    public function get_avg($_db_name)
    {
        $this->useDbConfig = $_db_name['user_data'];

        $params = array(
            'fields' => array(
                'gold', 'level'
            )
        );

        $data = $this->find('all', $params);

        $total_gold = 0;
        $total_level = 0;

        for($num = 0; $num < count($data); ++$num)
        {
            $total_gold += $data[$num]['UserChar']['gold'];
            $total_level += $data[$num]['UserChar']['level'];
        }

        $avg['gold'] = 0;
        $avg['level'] = 0;

        if(count($data) != 0)
        {
            $avg['gold'] = round($total_gold / count($data), 1);
            $avg['level'] = round($total_level / count($data), 1);
        }

        return $avg;
    }

    public function get_igs_user($_db_name)
    {
        $this->useDbConfig = $_db_name['user_data'];
        $params = array(
            'conditions' => array(
                'nick_name' => array('$regex' => 'IGS')
            ),
            'order' => array('le' => 'DESC')
        );

        $data = $this->find('all', $params);
        return $data;
    }
}